package com.wyh.service.serviceImpl.g3serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wyh.domain.po.g3po.*;
import com.wyh.domain.vo.g3vo.ExcelInfoVo;
import com.wyh.mapper.g3mapper.*;
import com.wyh.service.g3service.ChargingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.time.LocalDate;
import java.util.List;

@Service("g3ChargingService")
public class ChargingServiceImpl extends ServiceImpl<G3ChargingMapper, Charging> implements ChargingService {

    @Autowired
    G3ChargingMapper g3ChargingMapper;

    @Autowired
    G3ProjectMapper g3ProjectMapper;

    @Autowired
    ThreeMeterMapper threeMeterMapper;

    @Autowired
    ThreeMeterReadingMapper threeMeterReadingMapper;

    @Autowired
    ReadingSchemeMapper readingSchemeMapper;

    @Autowired
    G3ContractMapper g3ContractMapper;
    @Autowired
    ContractItemMapper contractItemMapper;
    @Autowired
    G3ResourceMapper g3ResourceMapper;

    @Override
    public int addCharging(Charging charging) {
        return g3ChargingMapper.insertCharging(charging);
    }


    //插入charging
    @Override                                              //资源id
    public boolean insertCharging(ExcelInfoVo excelInfoVo, int Rid, int userid) {


        Charging charging = new Charging();
        //判断是否三表类
        if (excelInfoVo.getMeterName() == null && excelInfoVo.getMeterNumber() == null && excelInfoVo.getLastMeterReading() == null && excelInfoVo.getCurrentMeterReading() == null && excelInfoVo.getDosage() == null) {
            charging.setBillingnature(0);
        } else {
            charging.setBillingnature(1);
        }

        //合同表信息
        G3Contract g3Contract = g3ContractMapper.selectOne(new QueryWrapper<G3Contract>().eq("resourceid", Rid));


        //合同费项表
        G3Contractitem g3Contractitem = contractItemMapper.selectOne(new QueryWrapper<G3Contractitem>()
                .eq("contractid", g3Contract.getId())
                .eq("name", excelInfoVo.getBillingitemsname()));
//
//        //资源表
        ResourceInfo resource = g3ResourceMapper.selectOne(new QueryWrapper<ResourceInfo>().eq("id", Rid));


        if (resource != null && g3Contractitem != null && g3Contract != null) {


            charging.setCustomerid(g3Contract.getCustomerid());//客户id
            charging.setContractid(g3Contract.getId());//合同id
            charging.setUnitpriceid(g3Contractitem.getItem());//费项id
            charging.setArea(resource.getBuildingarea());//这里有问题，资源表中有两个面积
            charging.setUpdatetime(new Timestamp(System.currentTimeMillis()));//修改时间
            charging.setResourcename(excelInfoVo.getResourcename());//资源名称
            charging.setResourceid(Rid);//资源id
            charging.setPropertyname(excelInfoVo.getPropertyname());//楼盘
            charging.setBuildingname(excelInfoVo.getBuildingname());//楼栋
            charging.setFloorname(excelInfoVo.getFloorname());//楼层
            charging.setBillingitemsname(excelInfoVo.getBillingitemsname());//费项名称
            charging.setCustomername(excelInfoVo.getCustomerName());//客户
            charging.setStarttime(new Timestamp(excelInfoVo.getStarttime().getTime()));//开始时间
            charging.setReceivable(excelInfoVo.getReceivable());//应收金额
            charging.setEndtime(new Timestamp(excelInfoVo.getEndtime().getTime()));//结束时间
            charging.setPrice(excelInfoVo.getPrice());//单价
            charging.setBillingtime(new Timestamp(excelInfoVo.getBillingtime().getTime()));//账期
            charging.setState(0);
            if (excelInfoVo.getDosage()!=null){
                charging.setDosage(excelInfoVo.getDosage());
            }
            charging.setUserid(userid);//用户id
            int insert = g3ChargingMapper.insert(charging);
            return insert > 0;
        } else {
            return false;
        }

    }

    //插入三表抄表表
    @Override                                                       //楼盘id     资源id
    public boolean insertThreeMeterReading(ExcelInfoVo excelInfoVo, int Pid, int Rid,int userid) {

        ThreeMeterReading threeMeterReading = new ThreeMeterReading();
        //三表id（通过三表表拿）1，本期抄表时间(无），读数1，抄表人id（拿不到）
        // ，抄表状态（看用量是否为null）1，账期1，用量1，方案id（三表表）1，
        // 上期抄表时间1，上期读数1，上期用量1
        //三表id
        if (!excelInfoVo.getMeterNumber().isEmpty() && !excelInfoVo.getMeterName().isEmpty()) {

            QueryWrapper<G3ThreeMeter> threeMeterQueryWrapper = new QueryWrapper<>();
            threeMeterQueryWrapper.eq("name", excelInfoVo.getMeterName())
                    .eq("number", excelInfoVo.getMeterNumber())
                    .eq("belongingid", Rid);


            G3ThreeMeter g3ThreeMeter = threeMeterMapper.selectOne(threeMeterQueryWrapper);












//增加
//            threeMeterReading.setNature(threeMeter.getNature());
//            &&threeMeter.getNature()!=0


            //增加if (threeMeter!=null){}else {
            //                return false;
            //            }






            if (g3ThreeMeter !=null){
                if (g3ThreeMeter.getId() != null && g3ThreeMeter.getScheme() != 0&& g3ThreeMeter.getNature()!=0) {
                    threeMeterReading.setMeterid(g3ThreeMeter.getId());//三表id
                    threeMeterReading.setReadingschemeid(g3ThreeMeter.getScheme());//方案id
                    threeMeterReading.setNature(g3ThreeMeter.getNature());
                }else {
                    return false;
                }
            }else {
                return false;
            }

        }
        if (excelInfoVo.getCurrentMeterReading() != null) {
            threeMeterReading.setReading(excelInfoVo.getCurrentMeterReading());//本期读数
        }

        //判断状态
        if (excelInfoVo.getCurrentMeterReading() != null && excelInfoVo.getDosage() != null) {
            threeMeterReading.setState(-1);//状态
            threeMeterReading.setDosage(excelInfoVo.getDosage());//用量
        } else if (excelInfoVo.getLastMeterReading() != 0.0) {
            threeMeterReading.setState(0);
        } else {
            threeMeterReading.setState(0);
        }
        threeMeterReading.setUserid(userid);

        if (excelInfoVo.getLastMeterReading() != 0.0) {//上期读数
            threeMeterReading.setPreviousreading(excelInfoVo.getLastMeterReading());
        }
        if (excelInfoVo.getLastReadingTime() != null) {//上期抄表时间
            threeMeterReading.setPreviousperiodtime(new Timestamp(excelInfoVo.getLastReadingTime().getTime()));
        }
        if (excelInfoVo.getBillingtime() != null) {//账期
            threeMeterReading.setTime(new Timestamp(excelInfoVo.getBillingtime().getTime()));
        }

        if (excelInfoVo.getLastPeriodUsage() != 0.0) {
            threeMeterReading.setPrevioususage(excelInfoVo.getLastPeriodUsage());//上期用量
        }
        threeMeterReading.setReadingtime(new Timestamp(System.currentTimeMillis()));


        int insert = threeMeterReadingMapper.insert(threeMeterReading);
        //修改抄表方案表

        Timestamp readingtime = threeMeterReading.getReadingtime();
        boolean b = updateReadingScheme(readingtime, threeMeterReading.getState(), Pid);
        if (insert > 0 && b) {
            return true;
        }
        return false;


    }

    //先通过楼盘id找到一些数据，然后循环通过时间找到唯一，如何修改
    @Override
    public boolean updateReadingScheme(Timestamp time, int state, int Pid) {

        QueryWrapper<G3ReadingScheme> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("development", Pid);
        LocalDate localDate = time.toLocalDateTime().toLocalDate();

        List<G3ReadingScheme> g3ReadingSchemes = readingSchemeMapper.selectList(queryWrapper);

        for (G3ReadingScheme g3ReadingScheme : g3ReadingSchemes) {
            LocalDate localDate1 = g3ReadingScheme.getTime().toLocalDateTime().toLocalDate();
            if (localDate.getYear() == localDate1.getYear() && localDate.getMonth() == localDate1.getMonth()) {//判断年月是否相等

                g3ReadingScheme.setQuantity(g3ReadingScheme.getQuantity() + 1);
                if (state == -1) {//已抄
                    //判断readingscheme中的state，-1抄完，0没有抄完
                    g3ReadingScheme.setQuantitycopied(g3ReadingScheme.getQuantitycopied() + 1);
                    if (g3ReadingScheme.getState() == -1) {
                        g3ReadingScheme.setEndingtime(time);
                    }
                } else {
//                    未抄
                    //判断readingscheme中的state，-1抄完，0没有抄完
                    g3ReadingScheme.setSurplus(g3ReadingScheme.getSurplus() + 1);
                    g3ReadingScheme.setEndingtime(null);
                    if (g3ReadingScheme.getState() == -1) {
                        g3ReadingScheme.setState(0);
                    }
                    UpdateWrapper<G3ReadingScheme> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("endingtime", null)
                            .eq("id", g3ReadingScheme.getId());
                    int i = readingSchemeMapper.update(null, updateWrapper);
                }
                int i = readingSchemeMapper.updateById(g3ReadingScheme);
                return i > 0;
            }
        }
        return false;
    }

    @Override
    public boolean insertChargingAndThreeReading(ExcelInfoVo excelInfoVo, int Pid, int Rid, int userid) {
        boolean insert = insertCharging(excelInfoVo, Rid, userid);
        if (insert) {

        } else {
            return false;
        }
        if (excelInfoVo.getMeterName() != null && excelInfoVo.getMeterNumber() != null && excelInfoVo.getMeterType() != null) {
            //插入 三表抄表表
            boolean b = insertThreeMeterReading(excelInfoVo, Pid, Rid,userid);

            return b;
        }
        return true;
    }

    @Override
    public ExcelInfoVo flats(ExcelInfoVo excelDatum, Integer name, int userid) {
        //通过楼盘名和园区id查楼盘id
        Integer projectId = g3ChargingMapper.findPId(excelDatum.getPropertyname(), name);

        if (projectId != null) {
            //组团、楼栋、单元
            if (excelDatum.getCluster() != null && !excelDatum.getCluster().isEmpty()) {//组团不为空
                Integer bId = g3ChargingMapper.findBId(excelDatum.getCluster(), projectId);//组团id
                if (bId != null) {
                    if (!excelDatum.getBuildingname().isEmpty()) {//楼栋不为空
                        Integer bId1 = g3ChargingMapper.findBId(excelDatum.getBuildingname(), bId);//楼栋id
                        if (bId1 != null) {
                            if (!excelDatum.getUnitname().isEmpty()) {//单元不为空
                                Integer bId2 = g3ChargingMapper.findBId(excelDatum.getUnitname(), bId1);//单元id
                                if (bId2 != null) {
                                    //查楼层
                                    Integer lId = g3ChargingMapper.findLId(excelDatum.getFloorname(), bId2);//楼层id
                                    if (lId != null) {
                                        Integer rId = g3ChargingMapper.findRId(excelDatum.getResourcename(), lId);//资源id
                                        if (rId != null) {
                                            //成功后插入
                                            boolean b = insertChargingAndThreeReading(excelDatum, projectId, rId, userid);
                                            if (b) {
                                                excelDatum.setResult(true);
                                                return excelDatum;
                                            } else {
                                                excelDatum.setErrorReason("该数据有误," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                                return excelDatum;
                                            }

                                        } else {
                                            excelDatum.setErrorReason("该楼层下没有该资源" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                            return excelDatum;
                                        }
                                    } else {
                                        excelDatum.setErrorReason("该单元下没有该楼层," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                        return excelDatum;
                                    }
                                } else {
                                    excelDatum.setErrorReason("该楼栋下没有该单元," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                    return excelDatum;

                                }
                            } else {//单元为空  楼栋不为空
                                //查楼层
                                Integer fid = g3ChargingMapper.findLId(excelDatum.getFloorname(), bId1);//楼层id
                                if (fid != null) {
                                    Integer rId = g3ChargingMapper.findRId(excelDatum.getResourcename(), fid);//资源id
                                    if (rId != null) {
                                        //成功后插入
                                        boolean b = insertChargingAndThreeReading(excelDatum, projectId, rId, userid);
                                        if (b) {
                                            excelDatum.setResult(true);
                                            return excelDatum;
                                        } else {
                                            excelDatum.setErrorReason("该数据有误," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                            return excelDatum;
                                        }
                                    } else {
                                        excelDatum.setErrorReason("该楼层下没有该资源," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                        return excelDatum;
                                    }
                                } else {
                                    excelDatum.setErrorReason("该单元下没有该楼层," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                    return excelDatum;
                                }
                            }

                        } else {
                            excelDatum.setErrorReason("该组团下未找到该楼栋," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                            return excelDatum;
                        }
                    } else {//楼栋为空  单元必须存在
                        Integer bId2 = g3ChargingMapper.findBId(excelDatum.getUnitname(), bId);//单元id
                        if (bId2 != null) {
                            //查楼层
                            Integer lId = g3ChargingMapper.findLId(excelDatum.getFloorname(), bId2);//楼层id
                            if (lId != null) {
                                Integer rId = g3ChargingMapper.findRId(excelDatum.getResourcename(), lId);//资源id
                                if (rId != null) {
                                    //成功后插入
                                    boolean b = insertChargingAndThreeReading(excelDatum, projectId, rId, userid);
                                    if (b) {
                                        excelDatum.setResult(true);
                                        return excelDatum;
                                    } else {
                                        excelDatum.setErrorReason("该数据有误" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                        return excelDatum;
                                    }


                                } else {
                                    excelDatum.setErrorReason("该楼层下没有该资源" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                    return excelDatum;
                                }
                            } else {
                                excelDatum.setErrorReason("该单元下没有该楼层" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                return excelDatum;
                            }
                        } else {
                            excelDatum.setErrorReason("该组团下没有该单元," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                            return excelDatum;
                        }
                    }
                } else {
                    excelDatum.setErrorReason("该楼盘下没有该组团" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                    return excelDatum;
                }
            } else {//组团为空  楼盘id projectId
                if (!excelDatum.getBuildingname().isEmpty()) {//楼栋不为空
                    Integer bId1 = g3ChargingMapper.findBId(excelDatum.getBuildingname(), projectId);//楼栋id
                    if (bId1 != null) {
                        if (excelDatum.getUnitname()!=null) {//单元不为空
                            Integer bId2 = g3ChargingMapper.findBId(excelDatum.getUnitname(), bId1);//单元id
                            if (bId2 != null) {
                                //查楼层
                                Integer lId = g3ChargingMapper.findLId(excelDatum.getFloorname(), bId2);//楼层id
                                if (lId != null) {
                                    Integer rId = g3ChargingMapper.findRId(excelDatum.getResourcename(), lId);//资源id
                                    if (rId != null) {
                                        //成功后插入
                                        boolean b = insertChargingAndThreeReading(excelDatum, projectId, rId, userid);
                                        if (b) {
                                            excelDatum.setResult(true);
                                            return excelDatum;
                                        } else {
                                            excelDatum.setErrorReason("该数据有误" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                            return excelDatum;
                                        }

                                    } else {
                                        excelDatum.setErrorReason("该楼层下没有该资源" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                        return excelDatum;
                                    }
                                } else {
                                    excelDatum.setErrorReason("该单元下没有该楼层" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                    return excelDatum;
                                }
                            } else {
                                excelDatum.setErrorReason("该楼栋下没有该单元" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                return excelDatum;
                            }
                        } else {//单元为空  楼栋不为空
                            //查楼层
                            Integer fid = g3ChargingMapper.findLId(excelDatum.getFloorname(), bId1);//楼层id
                            if (fid != null) {

                                Integer rId = g3ChargingMapper.findRId(excelDatum.getResourcename(), fid);//资源id

                                if (rId != null) {
                                    //成功后插入
                                    boolean b = insertChargingAndThreeReading(excelDatum, projectId, rId, userid);
//                                    sss
                                    if (b) {
                                        excelDatum.setResult(true);
                                        return excelDatum;
                                    } else {
                                        excelDatum.setErrorReason("该数据有误," + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                        return excelDatum;
                                    }

                                } else {
                                    excelDatum.setErrorReason("该楼层下没有该资源" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                    return excelDatum;
                                }
                            } else {
                                excelDatum.setErrorReason("该单元下没有该楼层" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                return excelDatum;
                            }
                        }

                    } else {
                        excelDatum.setErrorReason("该组团下未找到该楼栋" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                        return excelDatum;
                    }

                } else {//楼栋为空  单元必须不为空
                    Integer bId2 = g3ChargingMapper.findBId(excelDatum.getUnitname(), projectId);//单元id
                    if (bId2 != null) {
                        //查楼层
                        Integer lId = g3ChargingMapper.findLId(excelDatum.getFloorname(), bId2);//楼层id
                        if (lId != null) {
                            Integer rId = g3ChargingMapper.findRId(excelDatum.getResourcename(), lId);//资源id
                            if (rId != null) {
                                //成功后插入
                                boolean b = insertChargingAndThreeReading(excelDatum, projectId, rId, userid);
                                if (b) {
                                    excelDatum.setResult(true);
                                    return excelDatum;
                                } else {
                                    excelDatum.setErrorReason("该数据有误" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                    return excelDatum;
                                }

                            } else {
                                excelDatum.setErrorReason("该楼层下没有该资源" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                                return excelDatum;
                            }
                        } else {
                            excelDatum.setErrorReason("该单元下没有该楼层" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                            return excelDatum;
                        }
                    } else {
                        excelDatum.setErrorReason("该组团下没有该单元" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
                        return excelDatum;
                    }

                }
            }
        } else {
            excelDatum.setErrorReason("未找到该楼盘" + (excelDatum.getErrorReason() != null ? excelDatum.getErrorReason() : ""));
            return excelDatum;
        }

    }


}
